package com.jiehun.payment.cashier.domain.opp.weixin;


import java.io.File;
import java.io.FileInputStream;
import java.security.KeyStore;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;

import javax.net.ssl.SSLContext;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;



import org.apache.http.util.EntityUtils;






import lombok.Getter;
import lombok.Setter;


public class WeixinV3HttpsClient {

    private int socketTimeout = 10000;


    private int connectTimeout = 30000;


    private RequestConfig requestConfig;
	

    private CloseableHttpClient httpClient;    
        
    
    @Getter @Setter private File certPfxFile;
    
    @Getter @Setter private String certPfxPasswd;    
    
    
    public String doRequest(String uri, String xmlParams) {
    	try{
	        KeyStore keyStore = KeyStore.getInstance("PKCS12");
	        FileInputStream instream = new FileInputStream(certPfxFile);
	        try {
	            keyStore.load(instream, certPfxPasswd.toCharArray());
	        } catch (CertificateException e) {
	            e.printStackTrace();
	        } catch (NoSuchAlgorithmException e) {
	            e.printStackTrace();
	        } finally {
	            instream.close();
	        }
	
	        SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore,certPfxPasswd.toCharArray()).build();
	        // Allow TLSv1 protocol only
	        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
	                sslcontext,
	                new String[]{"TLSv1"},
	                null,
	                SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
	
	        httpClient = HttpClients.custom()
	                .setSSLSocketFactory(sslsf)
	                .build();
	        requestConfig = RequestConfig.custom().setSocketTimeout(socketTimeout).setConnectTimeout(connectTimeout).build();        
	        
	        String result = null;
	
	        HttpPost httpPost = new HttpPost(uri);
	
	
	        StringEntity postEntity = new StringEntity(xmlParams, "UTF-8");
	        httpPost.addHeader("Content-Type", "text/xml");
	        httpPost.setEntity(postEntity);
	        httpPost.setConfig(requestConfig);        
	   
	
	        try {
	            HttpResponse response = httpClient.execute(httpPost);
	
	            HttpEntity entity = response.getEntity();
	
	            result = EntityUtils.toString(entity, "UTF-8");
	
	        }catch (Exception e) {
	        	throw new RuntimeException("", e);
	
	        } finally {
	            httpPost.abort();
	        }
	
	        return result;
        
        
        
        
        
    	  } catch (Exception error) {
              throw new RuntimeException("", error);
          }
    	
    }
    
    public static void main(String[] args) {
    	WeixinV3HttpsClient client = new WeixinV3HttpsClient();        
        client.setCertPfxFile(new File("d:/1225397302_v3.p12"));
        client.setCertPfxPasswd("1225397302");
        
        String xml="<xml><appid>wxe45a7a3733400033</appid><mch_id>1225397302</mch_id>	<nonce_str>6cefdb308e1e2e8aabd48cf79e546a02</nonce_str>	<op_user_id>1225397302</op_user_id>	<out_refund_no>1415701182</out_refund_no>	<refund_fee>1</refund_fee>	<total_fee>1</total_fee>	<transaction_id>1007280737201509240979187234</transaction_id>	<sign>772F859DDA240EFFE53516A34B37EC25</sign></xml>";
        String response = client.doRequest("https://api.mch.weixin.qq.com/secapi/pay/refund",xml);
        
        System.out.println(response);
    	
    }
    
    
}
